package com.e3roid.examples;

import android.view.MotionEvent;
import android.widget.Toast;

import com.e3roid.E3Activity;
import com.e3roid.E3Engine;
import com.e3roid.E3Scene;
import com.e3roid.drawable.sprite.TiledSprite;
import com.e3roid.drawable.texture.TiledTexture;

public class TiledSpriteExample extends E3Activity {

	private final static int WIDTH  = 320;
	private final static int HEIGHT = 480;
	
	private TiledSprite  tile1;
	private TiledSprite  tile2;
	private TiledSprite  tile3;
	private TiledSprite  tile4;
	private TiledTexture tileTexture;

	@Override
	public E3Engine onLoadEngine() {
		E3Engine engine = new E3Engine(this, WIDTH, HEIGHT);
		engine.requestFullScreen();
		engine.requestPortrait();
		return engine;
	}

	@Override
	public E3Scene onLoadScene() {
		E3Scene scene = new E3Scene();
		scene.addEventListener(this);
		
		int centerX = (getWidth()  - (tileTexture.getTileWidth() * 4))  / 2;
		int centerY = (getHeight() - tileTexture.getTileHeight()) / 2;
		
		int tileWidth = tileTexture.getTileWidth();
		tile1 = new TiledSprite(tileTexture, centerX, centerY, 0, 0);
		tile2 = new TiledSprite(tileTexture, centerX + tileWidth, centerY, 1, 0);
		tile3 = new TiledSprite(tileTexture, centerX + (tileWidth * 2), centerY, 2, 0);
		tile4 = new TiledSprite(tileTexture, centerX + (tileWidth * 3), centerY, 3, 0);
		
		scene.getTopLayer().add(tile1);
		scene.getTopLayer().add(tile2);
		scene.getTopLayer().add(tile3);
		scene.getTopLayer().add(tile4);
		
		scene.setBackgroundColor(0f, 0f, 0f, 1);
		
		Toast.makeText(this, "Touch screen to change tile.", Toast.LENGTH_LONG).show();
		return scene;
	}

	@Override
	public void onLoadResources() {
		tileTexture  = new TiledTexture("blocks.png", 32, 32, 0, 0, 2, this);
	}

	@Override
	public boolean onSceneTouchEvent(E3Scene scene, MotionEvent motionEvent) {
		if (tile1 != null) {
			if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
				tile1.setTile(getNextTile(tile1.getTileIndexX()), 0);
				tile2.setTile(getNextTile(tile2.getTileIndexX()), 0);
				tile3.setTile(getNextTile(tile3.getTileIndexX()), 0);
				tile4.setTile(getNextTile(tile4.getTileIndexX()), 0);
			}
		}
		return false;
	}

	private int getNextTile(int x) {
		x = x + 1;
		if (x > 5) x = 0;
		return x;
	}
}